import React from 'react';
import {Icon, Input, InputNumber, Select} from "antd";
import 'styles/components/compact-input-select.scss'
const Option = Select.Option;

//todo: 扩充为支持Input
class CompactInputSelect extends React.Component {

  state = {
    value: ''
  };

  componentWillMount() {
    if ('value' in this.props) {
      const value = this.props.value;
      this.setState({ value: this._findValue(value) });
    }
  }

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      const value = nextProps.value;
      this.setState({ value: this._findValue(value) });
    }
  }

  _findKey = (record, key) =>{
    return (typeof key === 'string') ? record[key] : key(record)
  };

  _findValue = value => {
    const { selectorItem: { key, label }, options } = this.props;
    let selectedOptions = options.filter(i => value === this._findKey(i, key));
    return selectedOptions.length ? this._findKey(selectedOptions[0], label) : value;
  };

  onChange = changedValue => {
    const onChange = this.props.onChange;
    onChange && onChange(changedValue);
  };

  render() {
    const { value } = this.state;
    const { placeholder, disabled, selectorItem: { key, label }, parseValue, options } = this.props;
    let inputProps = {
      onChange: e => {
        let value = parseValue ? parseValue(e.target.value) : e.target.value;
        this.setState({ value });
        this.onChange(value);
      },
      value,
      placeholder,
      disabled
    };
    return (
      <div className="compact-input-select">
        <div className='compact-input-select-input'>
          <Input {...inputProps} />
        </div>
        <div className='compact-input-select-select-btn'>
          <Icon type="down" style={{cursor: 'pointer'}}/>
        </div>
        <Select
          showSearch
          getPopupContainer={triggerNode => triggerNode.parentNode}
          onSelect={this.onChange}
          disabled={disabled}
          optionLabelProp='title'
        >
          {options.map(optionItem => (
            <Option
              key={this._findKey(optionItem, key)}
              value={this._findKey(optionItem, key)}
              title={this._findKey(optionItem, label)}
              className={`compact-input-select-select-option`}
            >
              <div>
                <div>{this._findKey(optionItem, label)}</div>
                <div className="description">{optionItem.description}</div>
              </div>
            </Option>
          ))}
        </Select>

      </div>
    );
  }
}

export default CompactInputSelect;
